package com.flowershop.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flowershop.entity.Customer;
import com.flowershop.service.CustomerService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/customers")
@CrossOrigin
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginForm) {
        try {
            String username = loginForm.get("username");
            String password = loginForm.get("password");
            
            log.info("收到客户登录请求 - 用户名: {}", username);
            
            if (username == null || username.isEmpty()) {
                log.error("登录失败 - 用户名为空");
                return ResponseEntity.badRequest().body("用户名不能为空");
            }
            
            if (password == null || password.isEmpty()) {
                log.error("登录失败 - 密码为空");
                return ResponseEntity.badRequest().body("密码不能为空");
            }
            
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            // 先尝试用手机号登录
            queryWrapper.eq(Customer::getPhone, username)
                       .or()
                       // 如果手机号不匹配，再尝试用用户名登录
                       .eq(Customer::getName, username);
            
            Customer customer = customerService.getOne(queryWrapper);
            
            log.info("查询结果 - customer: {}", customer);
            
            if (customer == null) {
                log.error("登录失败 - 用户名不存在: {}", username);
                return ResponseEntity.badRequest().body("用户名或密码错误");
            }
            
            if (!password.equals(customer.getPassword())) {
                log.error("登录失败 - 密码错误 - 用户名: {}", username);
                return ResponseEntity.badRequest().body("用户名或密码错误");
            }
            
            // 生成简单的token
            String token = username + "_" + System.currentTimeMillis();
            
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("id", customer.getId());
            result.put("username", customer.getName());
            result.put("phone", customer.getPhone());
            result.put("email", customer.getEmail());
            result.put("points", customer.getPoints());
            
            log.info("客户登录成功 - 用户名: {}", username);
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("登录过程中发生错误", e);
            return ResponseEntity.internalServerError().body("服务器内部错误: " + e.getMessage());
        }
    }

    @GetMapping("/page")
    public Page<Customer> page(@RequestParam(defaultValue = "1") Integer current,
                             @RequestParam(defaultValue = "10") Integer size,
                             @RequestParam(required = false) String name) {
        Page<Customer> page = new Page<>(current, size);
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Customer::getName, name);
        }
        return customerService.page(page, queryWrapper);
    }

    @GetMapping("/{id}")
    public Customer getById(@PathVariable Long id) {
        return customerService.getById(id);
    }

    @PostMapping
    public ResponseEntity<?> save(@RequestBody Map<String, String> registerForm) {
        try {
            String username = registerForm.get("username");
            String password = registerForm.get("password");
            String phone = registerForm.get("phone");
            
            // 验证必填字段
            if (username == null || username.isEmpty()) {
                return ResponseEntity.badRequest().body("用户名不能为空");
            }
            if (password == null || password.isEmpty()) {
                return ResponseEntity.badRequest().body("密码不能为空");
            }
            if (phone == null || phone.isEmpty()) {
                return ResponseEntity.badRequest().body("手机号不能为空");
            }
            
            // 检查用户名是否已存在
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Customer::getName, username)
                       .or()
                       .eq(Customer::getPhone, phone);
            Customer existingCustomer = customerService.getOne(queryWrapper);
            
            if (existingCustomer != null) {
                if (existingCustomer.getName().equals(username)) {
                    return ResponseEntity.badRequest().body("用户名已被使用");
                }
                if (existingCustomer.getPhone().equals(phone)) {
                    return ResponseEntity.badRequest().body("手机号已被注册");
                }
            }
            
            // 创建新用户
            Customer customer = new Customer();
            customer.setName(username);  // 使用 username 字段作为 name
            customer.setPassword(password);
            customer.setPhone(phone);
            customer.setPoints(0);  // 初始积分为0
            
            customerService.save(customer);
            
            // 返回成功响应
            Map<String, Object> result = new HashMap<>();
            result.put("id", customer.getId());
            result.put("username", customer.getName());
            result.put("phone", customer.getPhone());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("注册失败", e);
            return ResponseEntity.internalServerError().body("注册失败：" + e.getMessage());
        }
    }

    @PutMapping
    public Customer update(@RequestBody Customer customer) {
        customerService.updateById(customer);
        return customer;
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Long id) {
        return customerService.removeById(id);
    }

    @PutMapping("/{id}/points")
    public boolean updatePoints(@PathVariable Long id, @RequestParam Integer points) {
        Customer customer = customerService.getById(id);
        if (customer != null) {
            customer.setPoints(points);
            return customerService.updateById(customer);
        }
        return false;
    }
} 